package com.uziot.bucket.auth;

import com.alibaba.fastjson.JSON;
import com.xkcoding.justauth.AuthRequestFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className TestAuthController
 * @date 2021-08-08 23:21:33
 * @description 自定义通过第三方登录系统接口
 */

@Slf4j
@Controller
@RequestMapping("/oauth")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TestAuthController {
    private final AuthRequestFactory authRequestFactory;

    @GetMapping(value = "list")
    public @ResponseBody
    List<String> list() {
        return authRequestFactory.oauthList();
    }

    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = authRequestFactory.get(type);
        String state = AuthStateUtils.createState();
        String authorize = authRequest.authorize(state);
        response.sendRedirect(authorize);
    }

    @GetMapping(value = "/callback/{type}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String login(@PathVariable String type, AuthCallback callback, Model model,HttpServletResponse resp) throws IOException {
        AuthRequest authRequest = authRequestFactory.get(type);
        AuthResponse<?> response = authRequest.login(callback);
        log.info("【response】= {}", JSON.toJSONString(response));
        AuthUser authUser = (AuthUser) response.getData();
        model.addAttribute("authUser",authUser);
        return "index";
    }
}